import { StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native';
import React, { useEffect, useState, useRef } from 'react';
import { useNavigation, useRoute } from '@react-navigation/native';
import { userBindDeviceApi, unbindDeviceApi, getDeviceDetails } from '~/api/deviceApi';
import { bindDevicesXueWei, unbindDevicesXueWei } from '~/api/acupoints';
import { useTranslation } from 'react-i18next';
import { NavBarHeader, MyLoading, DialogModal } from '~/components';
import { px2dp, scale, width } from '~/utils/px2dp';
import { appStore, deviceStore, userStore, observer } from '~/store';
import { applyAcupoints, wifiDevices } from '~/utils/deviceMenues';
import { setPositionTag } from '~/utils/ble/application';

export default observer(() => {
    const { t } = useTranslation();
    const navigation: any = useNavigation();
    const router: any = useRoute();
    const loadingRef = useRef<any>();
    const {
        device_sn,
        routePage = '',
        body_index = '',
        course_id = '',
        titleId = '',
        actionType,
        id,
        write_id,
        oldDeviceSn,
    } = router?.params || {};
    const [deviceInfo, setDeviceInfo] = useState<any>({});
    const getData = () => {
        getDeviceDetails({ device_sn }).then((res) => {
            if (res.status == 1) {
                const data = res.data;
                data.num = data.device_sn.substring(device_sn.length - 3);
                setDeviceInfo(data);
            } else {
                if (res.msg == '设备不存在,请联系客服!') {
                    Toast.show({ content: t('ScanDeviceResult.t1'), layout: 'top' });
                } else {
                    Toast.show({ content: res.msg });
                }
            }
        });
    };
    // 假如是五穴项目
    const acupoints = () => {
        if (applyAcupoints.indexOf(deviceInfo.device_code) !== -1) {
            const searchDevices = deviceStore.device.searchDevices || [];
            const matchedDevice = searchDevices.find((device) => device.device_sn === device_sn) || {
                device_sn: '',
                id: '',
            };
            // 假如是解绑穴位
            if (actionType == 'unbind') {
                if (device_sn !== oldDeviceSn) {
                    loadingRef.current.hideLoading();
                    Toast.show({ content: t('AddDeviceScreen.t50') });
                    return;
                }
                deviceStore.connectBle(matchedDevice, (res) => {
                    loadingRef.current.hideLoading();
                    if (res.status == 2) {
                        Toast.show({ content: t('ScanDeviceResult.t8') });
                        return;
                    }
                    setPositionTag(0);
                    setTimeout(() => {
                        unbindDevicesBox();
                    }, 500);
                });
            } else {
                deviceStore.connectBle(matchedDevice, (res) => {
                    loadingRef.current.hideLoading();
                    if (res.status == 2) {
                        Toast.show({ content: t('ScanDeviceResult.t8') });
                        return;
                    }
                    setPositionTag(body_index);
                    setTimeout(() => {
                        bindDevicesbody();
                    }, 500);
                });
                // 假如是绑定穴位
            }
        } else {
            loadingRef.current.showLoading();
            Toast.show({ content: t('AddDeviceScreen.t47') });
        }
    };
    // 解绑穴位
    const unbindDevicesBox = () => {
        unbindDevicesXueWei({ id }).then((res) => {
            loadingRef.current.hideLoading();
            deviceStore.disConnectble();
            navigation.navigate('AddDeviceScreen', { titleId });
        });
    };
    // 绑定学位
    const bindDevicesbody = () => {
        bindDevicesXueWei({ device_sn: device_sn, body_index: body_index, course_id: course_id, write_id })
            .then((res) => {
                if (res.status == 0) {
                    Toast.show({ content: res.msg, layout: 'top' });
                } else {
                    Toast.show({ content: t('AddDeviceScreen.t33'), layout: 'top' });
                    navigation.navigate('AddDeviceScreen', {
                        titleId,
                        subDeviceSn: deviceInfo.device_sn,
                        isBleWriteCorse: 'isBleWriteCorse',
                    });
                }
            })
            .catch((err) => {
                loadingRef.current.hideLoading();
                Toast.show({ content: t('AddDeviceScreen.t32'), layout: 'top' });
            });
    };
    const [visible, setVisible] = useState(false); // 配网
    const onConfirm = () => {
        const searchDevices = deviceStore.device.searchDevices || [];
        const matchedDevice = searchDevices.find((device) => device.device_sn == device_sn) || {
            device_sn: '',
            id: '',
        };
        deviceStore.connectBle(matchedDevice, (res) => {
            if (res.status == 2) {
                Toast.show({ content: t('ScanDeviceResult.t8') });
                setVisible(false);
                return;
            }
            setVisible(false);
            navigation.navigate('DeviceWifi');
        });
    };
    const addDevice = async () => {
        try {
            await unbindDeviceApi({ device_sn });
            const res = await userBindDeviceApi({ device_sn });
            if (res.status === 1) {
                // 假如wifi设备
                if (wifiDevices.indexOf(deviceInfo.device_code) !== -1) {
                    setVisible(true);
                    return;
                }
                if (routePage == 'Acupoints') {
                    //假如是五穴项目
                    loadingRef.current.showLoading();
                    acupoints();
                    return;
                }
                if (userStore.userBindDeviceData.length == 0) {
                    userStore.signAutoConnectDevice(device_sn);
                }
                navigation.navigate('Main');
            } else {
                Toast.show({ content: res.msg, layout: 'top' });
            }
        } catch (error) {
            loadingRef.current.hideLoading();
        }
    };
    useEffect(() => {
        getData();
    }, []);

    return (
        <View style={styles.container}>
            <NavBarHeader title={t('ScanDeviceResult.t2')} />
            <View style={[styles.list_item, styles.flex]}>
                <Image
                    source={{
                        uri: deviceInfo.device_image
                            ? deviceInfo.device_image
                            : 'https://bjy-dev.oss-cn-shenzhen.aliyuncs.com/xcx/images/typeWatch.png',
                    }}
                    style={styles.icons}
                />
                <View style={styles.info}>
                    {appStore.app.language == 'zh' ? (
                        <Text style={styles.title}>
                            {deviceInfo.num}
                            {t('ScanDeviceResult.t3')}
                            {deviceInfo.armarium_device_name}
                        </Text>
                    ) : (
                        <Text style={styles.title}>
                            {t('ScanDeviceResult.t3')}
                            {deviceInfo.num}
                            {/* {deviceInfo.armarium_device_name} */}
                        </Text>
                    )}
                    <Text style={styles.t1}>SN：{deviceInfo.device_sn}</Text>
                    <Text style={styles.t1}>
                        {t('ScanDeviceResult.t4')}：{deviceInfo.device_code}
                    </Text>
                </View>
            </View>
            <View style={styles.bottom}>
                <TouchableOpacity style={styles.bootom_button} onPress={addDevice}>
                    {routePage == 'Acupoints' ? (
                        <Text style={styles.bootom_buttonText}>
                            {actionType == 'unbind' ? t('ScanDeviceResult.t6') : t('ScanDeviceResult.t7')}
                        </Text>
                    ) : (
                        <Text style={styles.bootom_buttonText}>{t('ScanDeviceResult.t5')}</Text>
                    )}
                </TouchableOpacity>
            </View>
            <MyLoading ref={loadingRef} />
            <DialogModal
                visible={visible}
                content={t('ScanDeviceResult.t9')}
                onCancel={() => {
                    setVisible(false);
                    if (userStore.isRole == 'Acupoints') {
                        navigation.navigate('AcupointsScreen');
                    } else {
                        navigation.navigate('Main');
                    }
                }}
                onConfirm={() => onConfirm()}
            />
        </View>
    );
});

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F5f5f5',
    },
    info: {
        marginLeft: px2dp(30),
    },
    title: {
        fontSize: scale(30),
        fontWeight: 'bold',
        color: '#191919',
    },
    t1: {
        color: '#a4a4a4',
        fontSize: scale(24),
        marginTop: px2dp(12),
    },
    flex: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    list_item: {
        backgroundColor: '#fff',
        marginTop: px2dp(32),
        padding: px2dp(24),
        borderRadius: px2dp(20),
        marginHorizontal: px2dp(32),
    },
    icons: {
        width: px2dp(120),
        height: px2dp(120),
    },
    bottom: {
        backgroundColor: '#fff',
        paddingVertical: px2dp(60),
        position: 'absolute',
        bottom: 0,
        width: width,
    },
    bootom_button: {
        backgroundColor: '#242D56',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(16),
        height: px2dp(100),
        marginHorizontal: px2dp(32),
    },
    bootom_buttonText: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
});
